package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.business.rule.BusinessRuleUserPermissionHelp;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupSeniorSortPojo;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorSortDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorSortSaveDTO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSeniorSortSaveVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSeniorSortVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorSortEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.model.PublicGroupSeniorSortModel;
import com.xbongbong.saas.service.PublicGroupSeniorSortService;
import com.xbongbong.saas.service.PublicGroupService;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author lijiangren
 * @date 2022/4/15 14:12
 */
@Service("publicGroupSeniorSortService")
public class PublicGroupSeniorSortServiceImpl implements PublicGroupSeniorSortService {
    private static final Logger LOG = LoggerFactory.getLogger(PublicGroupSeniorSortServiceImpl.class);

    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;
    @Resource
    private PublicGroupService publicGroupService;
    @Resource
    private PublicGroupSeniorSortModel publicGroupSeniorSortModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private BusinessRuleUserPermissionHelp businessRuleUserPermissionHelp;
    @Resource
    private CommonHelp commonHelp;

    @Override
    public PublicGroupSeniorSortVO getListByFormIdAndCreatorId(PublicGroupSeniorSortDTO publicGroupSeniorSortDTO) throws XbbException {
        try {
            Long formId = publicGroupSeniorSortDTO.getFormId();
            String corpid = publicGroupSeniorSortDTO.getCorpid();
            UserVO userVO = publicGroupSeniorSortDTO.getLoginUser();
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(publicGroupSeniorSortDTO.getLoginUser(), userEntity);

            //需要loginuser(postman测试代码)
            //UserVO userVO = userService.getUserVO(corpid, publicGroupSeniorSortDTO.getUserId(), true, true);
            //UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(userVO, userEntity);
            PublicGroupSeniorSortVO publicGroupSeniorSortVO = new PublicGroupSeniorSortVO();
            List<PublicGroupSeniorSortPojo> publicGroupSeniorSortPojoList = new ArrayList<>();

            //根据formId获取公海池分组列表
            List<PublicGroupSeniorEntity> allGroupList = publicGroupSeniorModel.getByFormId(formId, corpid,BasicConstant.ZERO);
            allGroupList.removeIf(item -> Objects.equals(item.getStatus(), BasicConstant.ZERO));
            if (CollectionsUtil.isNotEmpty(allGroupList)) {
                //对分组列表进行权限过滤,返回的列表是当前登陆人具有查看权限的
                if (!(userVO.isAdminOrBoss() || userVO.isMaxDataPermission())) {
                    allGroupList = publicGroupService.filterGroupSeniorByUser(allGroupList, userEntity);
                    if (CollectionsUtil.isEmpty(allGroupList)) {
                        //无任何分组的查看权限
                        return publicGroupSeniorSortVO;
                    }
                }

                //按照层级、排序结果
                List<PublicGroupSeniorEntity> resultList = new ArrayList<>(allGroupList.size());
                getGroupSeniorList(allGroupList, BasicConstant.ZERO_LONG, resultList);
                //根据登录人ID和表单ID查询排序表
                List<PublicGroupSeniorSortEntity> publicGroupSeniorSortEntities = publicGroupSeniorSortModel.getListByFormIdAndCreatorId(corpid,formId,userVO.getUserId());
                if (CollectionsUtil.isNotEmpty(publicGroupSeniorSortEntities)) {
                    //转换成Map<分组ID,分组实体>
                    List<PublicGroupSeniorSortPojo> publicGroupSeniorSortPojos = convertPublicGroupSeniorList(formId, userVO, resultList, publicGroupSeniorSortEntities);
                    publicGroupSeniorSortPojoList.addAll(publicGroupSeniorSortPojos);
                } else {
                    //“全部” + 无分组 + 其他
                    List<PublicGroupSeniorSortPojo> publicGroupSeniorSortPojos = convertPublicGroupSeniorList(formId, userVO, resultList, null);
                    publicGroupSeniorSortPojoList.addAll(publicGroupSeniorSortPojos);
                }
            } else {
                //初始化一个全部分组
                PublicGroupSeniorSortPojo publicGroupSeniorSort = new PublicGroupSeniorSortPojo();
                publicGroupSeniorSort.setFormId(formId);
                publicGroupSeniorSort.setGroupId(0L);
                publicGroupSeniorSort.setGroupName("全部");
                publicGroupSeniorSort.setCreatorId(userVO.getUserId());
                publicGroupSeniorSort.setSort(0);
                publicGroupSeniorSort.setDefaultGroupCode(BasicConstant.ZERO);
                publicGroupSeniorSortPojoList.add(publicGroupSeniorSort);
            }
            publicGroupSeniorSortVO.setListGroupList(publicGroupSeniorSortPojoList);
            publicGroupSeniorSortVO.setShowSetting(true);
            setSaasSwimLaneView(publicGroupSeniorSortVO, publicGroupSeniorSortDTO);
            return publicGroupSeniorSortVO;
        } catch (Exception e) {
            LOG.error("getListByFormIdAndCreatorId数据库查询数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * @Author mingliang
     * @Description 设置saas表单的泳道视图按钮
     * @Date 2021/11/24 9:36
     * @param groupListVO
     * @param groupListDTO
     **/
    private void setSaasSwimLaneView(PublicGroupSeniorSortVO groupListVO, PublicGroupSeniorSortDTO groupListDTO) {
        try {
            groupListVO.setIsSwimLaneView(0);
            Integer distributorMark = groupListDTO.getDistributorMark();
            if (Objects.equals(distributorMark,1)){
                return;
            }
            PaasFormExplainEntity formExplainEntity = paasFormExplainModel.getByFormId(groupListDTO.getFormId(), groupListDTO.getCorpid());
            if (Objects.isNull(formExplainEntity)){
                return;
            }
            List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(formExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(formExplainEntity.getExplains(), null);
            Integer businessType = groupListDTO.getBusinessType();
            if (!Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)
                    && !Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)
                    && !Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)
                    && !Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType)
                    && !Objects.equals(SaasMarkEnum.PAAS.getCode(),groupListDTO.getSaasMark())) {
                return;
            }
            if (CollectionsUtil.isEmpty(fieldAttrEntityList)){
                groupListVO.setIsSwimLaneView(1);
                return;
            }
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(groupListDTO, handlerExplainDTO);
            handlerExplainDTO.setOwnerId(new ArrayList<>());
            handlerExplainDTO.setCoUserId(new ArrayList<>());
            //saas表单：高级版旗舰版有阶段视图按钮，paas表单：仅旗舰版有阶段视图
            Integer feeType = businessRuleUserPermissionHelp.getFeeType(groupListDTO.getCorpid());
            // 判断阶段推进器字段可见权限
            if (Objects.equals(groupListDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                if (!Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType) && !Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                    return;
                }
                if (!CommonHelp.ifStageOpen(businessType, explainMap, handlerExplainDTO)) {
                    return;
                }
                for (FieldAttrEntity temp : fieldAttrEntityList) {
                    String attr = temp.getAttr();
                    Integer isOpen = temp.getIsOpen();
                    if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)
                            && Objects.equals(CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), attr)
                            && Objects.equals(isOpen, 1)) {
                        groupListVO.setIsSwimLaneView(1);
                        return;
                    }
                    if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)
                            && Objects.equals(SalesOpportunityEnum.SALE_STAGE.getAttr(), attr)
                            && Objects.equals(isOpen, 1)) {
                        groupListVO.setIsSwimLaneView(1);
                        return;
                    }
                    if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)
                            && Objects.equals(ClueEnum.CLUE_STAGE.getAttr(), attr)
                            && Objects.equals(isOpen, 1)) {
                        groupListVO.setIsSwimLaneView(1);
                        return;
                    }
                    if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType)
                            && Objects.equals(temp.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())
                            && !ExplainUtil.isFieldNeedHide(temp, handlerExplainDTO)
                            && Objects.equals(temp.getIsOpen(), 1)) {
                        groupListVO.setIsSwimLaneView(1);
                        return;
                    }
                }
            } else if (Objects.equals(groupListDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                    return;
                }
                for (FieldAttrEntity temp : fieldAttrEntityList) {
                    if (Objects.equals(temp.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())
                            && !ExplainUtil.isFieldNeedHide(temp, handlerExplainDTO)
                            && Objects.equals(temp.getIsOpen(), 1)) {
                        groupListVO.setIsSwimLaneView(1);
                        return;
                    }
                }
            }
        } catch (XbbException e) {
            return;
        }
    }

    @Override
    public PublicGroupSeniorSortSaveVO saveGroupSort(PublicGroupSeniorSortSaveDTO publicGroupSeniorSortSaveDTO) throws XbbException {
        try {
            //根据formId和createId查询排序设置表
            String corpid = publicGroupSeniorSortSaveDTO.getCorpid();
            Long formId = publicGroupSeniorSortSaveDTO.getFormId();
            String userId = publicGroupSeniorSortSaveDTO.getUserId();
            List<PublicGroupSeniorSortEntity> groupSeniorSortEntityList = publicGroupSeniorSortSaveDTO.getListGroupList();
            List<PublicGroupSeniorSortEntity> dbGroupSeniorSortEntities = publicGroupSeniorSortModel.getListByFormIdAndCreatorId(corpid,formId,userId);
            if (CollectionsUtil.isEmpty(dbGroupSeniorSortEntities)) {
                //前端传入的顺序直接保存，批量插入
                publicGroupSeniorSortModel.insertBatch(groupSeniorSortEntityList);
            } else {
                if (CollectionsUtil.isEmpty(groupSeniorSortEntityList)) {
                    //将dbGroupSeniorSortEntities全部更新del = 1
                    publicGroupSeniorSortModel.updateBatchDel(dbGroupSeniorSortEntities, corpid);
                } else {
                    //有交集的数据
                    List<Long> groupIdS = groupSeniorSortEntityList.stream().map(PublicGroupSeniorSortEntity::getGroupId).collect(Collectors.toList());
                    List<Long> dbGroupIdS = dbGroupSeniorSortEntities.stream().map(PublicGroupSeniorSortEntity::getGroupId).collect(Collectors.toList());
                    List<Long> updateGroupIdS = groupIdS.stream().filter(item -> dbGroupIdS.contains(item)).collect(Collectors.toList());
                    //取补集
                    if (CollectionsUtil.isNotEmpty(updateGroupIdS)) {
                        groupIdS.removeAll(updateGroupIdS);
                        dbGroupIdS.removeAll(updateGroupIdS);
                    }
                    if (CollectionsUtil.isNotEmpty(updateGroupIdS)) {
                        //update  updateGroupIdS  更新整个传入数据
                        List<PublicGroupSeniorSortEntity> updateList = groupSeniorSortEntityList.stream().filter(item -> updateGroupIdS.contains(item.getGroupId())).collect(Collectors.toList());
                        if (CollectionsUtil.isNotEmpty(updateList)) {
                            publicGroupSeniorSortModel.updateBatch(updateList, corpid);
                        }
                    }
                    if (CollectionsUtil.isNotEmpty(groupIdS)) {
                        //insert  groupIdS
                        List<PublicGroupSeniorSortEntity> insertList = groupSeniorSortEntityList.stream().filter(item -> groupIdS.contains(item.getGroupId())).collect(Collectors.toList());
                        if (CollectionsUtil.isNotEmpty(insertList)) {
                            publicGroupSeniorSortModel.insertBatch(insertList);
                        }
                    }
                    if (CollectionsUtil.isNotEmpty(dbGroupIdS)) {
                        //update  del = 1  dbGroupIdS
                        List<PublicGroupSeniorSortEntity> updateDelList = dbGroupSeniorSortEntities.stream().filter(item -> dbGroupIdS.contains(item.getGroupId())).collect(Collectors.toList());
                        if (CollectionsUtil.isNotEmpty(updateDelList)) {
                            publicGroupSeniorSortModel.updateBatchDel(updateDelList, corpid);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("saveGroupSort设置排序失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return null;
    }

    /**
     * 实体转换
     * @author lijiangren
     * @date 2022-04-18 11 25
     */
    private List<PublicGroupSeniorSortPojo>  convertPublicGroupSeniorList(Long formId, UserVO user,List<PublicGroupSeniorEntity> publicGroupSeniorEntities, List<PublicGroupSeniorSortEntity> publicGroupSeniorSortEntities) {
        List<PublicGroupSeniorSortPojo> publicGroupSeniorSortPojoList = new ArrayList<>();
        if (CollectionsUtil.isEmpty(publicGroupSeniorSortEntities) ) {
            //处理“全部分组”，默认放在最前面
            PublicGroupSeniorSortPojo publicGroupSeniorSort = new PublicGroupSeniorSortPojo();
            publicGroupSeniorSort.setFormId(formId);
            publicGroupSeniorSort.setGroupId(0L);
            publicGroupSeniorSort.setGroupName("全部");
            publicGroupSeniorSort.setCreatorId(user.getUserId());
            publicGroupSeniorSort.setSort(0);
            publicGroupSeniorSort.setDefaultGroupCode(BasicConstant.ZERO);
            publicGroupSeniorSortPojoList.add(publicGroupSeniorSort);
            publicGroupSeniorEntities.forEach(item -> {
                PublicGroupSeniorSortPojo publicGroupSeniorSortPojo = new PublicGroupSeniorSortPojo();
                publicGroupSeniorSortPojo.setGroupId(item.getId());
                publicGroupSeniorSortPojo.setGroupName(item.getName());
                publicGroupSeniorSortPojo.setCreatorId(user.getUserId());
                publicGroupSeniorSortPojo.setFormId(item.getFormId());
                publicGroupSeniorSort.setDefaultGroupCode(BasicConstant.ZERO);
                publicGroupSeniorSortPojoList.add(publicGroupSeniorSortPojo);
            });
        } else if (CollectionsUtil.isNotEmpty(publicGroupSeniorSortEntities)){
            //处理排序设置表中的分组和分组表进行对比
            Map<Long, PublicGroupSeniorEntity> publicGroupSeniorMap = publicGroupSeniorEntities.stream().collect(Collectors.toMap(PublicGroupSeniorEntity::getId, publicGroupSeniorEntity -> publicGroupSeniorEntity));
            publicGroupSeniorSortEntities.forEach(item -> {
                PublicGroupSeniorSortPojo publicGroupSeniorSortPojo = new PublicGroupSeniorSortPojo();
                PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorMap.get(item.getGroupId());
                if (Objects.nonNull(publicGroupSeniorEntity)) {
                    publicGroupSeniorSortPojo.setGroupId(publicGroupSeniorEntity.getId());
                    publicGroupSeniorSortPojo.setGroupName(publicGroupSeniorEntity.getName());
                    publicGroupSeniorSortPojo.setCreatorId(user.getUserId());
                    publicGroupSeniorSortPojo.setFormId(publicGroupSeniorEntity.getFormId());
                    publicGroupSeniorSortPojo.setSort(item.getSort());
                    publicGroupSeniorSortPojo.setId(item.getId());
                    publicGroupSeniorSortPojo.setDefaultGroupCode(BasicConstant.ZERO);
                    publicGroupSeniorSortPojoList.add(publicGroupSeniorSortPojo);
                    publicGroupSeniorMap.remove(item.getGroupId());
                } else {
                    //有可能是"全部"分组(该分组表中未保存)
                    if (Objects.equals(item.getGroupId(),BasicConstant.ZERO_LONG)) {
                        publicGroupSeniorSortPojo.setGroupId(BasicConstant.ZERO_LONG);
                        publicGroupSeniorSortPojo.setGroupName("全部");
                        publicGroupSeniorSortPojo.setCreatorId(user.getUserId());
                        publicGroupSeniorSortPojo.setFormId(item.getFormId());
                        publicGroupSeniorSortPojo.setId(item.getId());
                        publicGroupSeniorSortPojo.setDefaultGroupCode(BasicConstant.ZERO);
                        publicGroupSeniorSortPojoList.add(publicGroupSeniorSortPojo);
                        publicGroupSeniorMap.remove(item.getGroupId());
                    }
                }
            });

            //新增的分组
            if (publicGroupSeniorMap != null && publicGroupSeniorMap.size() > 0) {
                Set<Long> groupIds = publicGroupSeniorMap.keySet();
                for (Long groupId : groupIds) {
                    PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorMap.get(groupId);
                    PublicGroupSeniorSortPojo publicGroupSeniorSortPojo = new PublicGroupSeniorSortPojo();
                    publicGroupSeniorSortPojo.setGroupId(publicGroupSeniorEntity.getId());
                    publicGroupSeniorSortPojo.setGroupName(publicGroupSeniorEntity.getName());
                    publicGroupSeniorSortPojo.setCreatorId(user.getUserId());
                    publicGroupSeniorSortPojo.setFormId(publicGroupSeniorEntity.getFormId());
                    publicGroupSeniorSortPojo.setDefaultGroupCode(BasicConstant.ZERO);
                    publicGroupSeniorSortPojoList.add(publicGroupSeniorSortPojo);
                }
            }
        }

        return publicGroupSeniorSortPojoList;
    }

    /**
     * 根据parentId递归组合新的分组列表
     * @author lijiangren
     * @date 2022-04-18 11 25
     */
    private void getGroupSeniorList(List<PublicGroupSeniorEntity> allGroupList, Long groupId, List<PublicGroupSeniorEntity> groupSeniorEntityArrayList) {
        if (CollectionsUtil.isNotEmpty(allGroupList)) {
            List<PublicGroupSeniorEntity> collect = allGroupList.stream().filter(item -> Objects.equals(item.getParentId(), groupId)).collect(Collectors.toList());
            if (CollectionsUtil.isNotEmpty(collect)) {
                for (PublicGroupSeniorEntity publicGroupSeniorEntity : collect) {
                    groupSeniorEntityArrayList.add(publicGroupSeniorEntity);
                    getGroupSeniorList(allGroupList, publicGroupSeniorEntity.getId(), groupSeniorEntityArrayList);
                }
                allGroupList.removeAll(collect);
            }
        }
    }
}
